﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleMap.Binders;
using SimpleMap.Setters;
using System.Reflection;
using System.Linq.Expressions;

namespace SimpleMap.Extractors
{
    public class CustomExtractor<T>:IValueBindingExtractor<T>
    {


        private List<IValueBinding<T>> _elements = new List<IValueBinding<T>>();


        public static CustomExtractor<T> CreateAuto(IPropertyValueSetterFactory<T> setterFactory) 
        {

            IValueBindingExtractor<T> e = new PropertyBindingExtractor<T>(setterFactory);
            return new CustomExtractor<T>(e);
        }
        
        public CustomExtractor(IValueBindingExtractor<T> extractor) 
        {

            _elements = extractor.Extract();
        }


        public void AddBinding(string column, PropertyInfo p)
        {
            _elements.Add(new ValueBinding<T>(new DynamicILPropertyValueSetter<T>(p),column));
        }


        public void ChangeBinding(string column, PropertyInfo p) 
        {

            foreach (IValueBinding<T> b in _elements) 
            {
                if (b.Setter.Name == p.Name) 
                {
                    b.Column = column;
                }
            }

        }

        public void ChangeBinding(string column, Expression<Func<T, object>> property)
        {

            MemberExpression m = (MemberExpression)property.Body;
            PropertyInfo p= m.Member.ReflectedType.GetProperty(m.Member.Name);
           
            this.ChangeBinding(column,p);
        }


        public void AddBinding(string column, Expression<Func<T, object>> property)
        {

            MemberExpression m = (MemberExpression)property.Body;
            PropertyInfo p = m.Member.ReflectedType.GetProperty(m.Member.Name);

          
             this.AddBinding(column, p);

        }


        public List<IValueBinding<T>> Extract()
        {
            return _elements;
        }
    }
}
